package com.google.code.gestion_de_conferences;


import java.util.ArrayList;
import java.util.Iterator;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class UsersListActivity extends ListActivity 
{
        AABDatabaseManager db;
        boolean haveUsers;

        /**
         * This function is launched when the activity is launched
         * 
         * @author Hyame Alameddine <hyame.alameddine@gmail.com>
         * 
         */
        public void onCreate(Bundle icicle) 
        {
            super.onCreate(icicle);
            
            haveUsers = this.displayUsers();
            if(haveUsers)
            {
                    //Get the list view
                    ListView list =  getListView();
                    //register the context menu for the listview
                    registerForContextMenu(list);
            }
        }
        
        /**
         * This function display the list of users (without the admin)
         * 
         * @author Hyame Alameddine <hyame.alameddine@gmail.com> 
         */
        public boolean displayUsers()
        {                 
            boolean returnValue = false;
            User user = new User();
            db = new AABDatabaseManager(this);
            String is_admin = "1";   
            ArrayList<ArrayList<Object>> allUsersArrays = new ArrayList<ArrayList<Object>>();
            
            //Get all users in the db
            allUsersArrays = db.getTablesRowsAsArrays (user);       
            String[] values = new String[0];
            int user_count=0;
            //check if we only have the admin then we have no users to display                                                                          
            if(allUsersArrays.size()<=1)
            {
                values = new String[1];
                values[0] = "No items to display";
                returnValue = false;
            }
            else if( allUsersArrays.size()>1)
            {
                returnValue = true;
                values = new String[allUsersArrays.size()-1];
                //array that will hold user data to be displayed
                for (int position=0; position < allUsersArrays.size(); position++)
                {
                    ArrayList<Object> row = allUsersArrays.get(position);                           
                    //check the is_admin value
                    if(!(row.get(6)).equals(is_admin) )
                    {                               
                            //display full name - company
                            values[user_count] = row.get(1).toString()+"-"+row.get(3).toString();    
                            user_count=user_count+1;
                    }                                                               
                } 
             }                       
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.user_row_layout, R.id.label, values);
            setListAdapter(adapter);
            return returnValue;
        }
        /**
         * This function allow to create the context menu when clicking on a user
         * 
         * @author Hyame Alameddine <hyame.alameddine@gmail.com>
         * 
         * @param ContextMenu menu
         * @param View v
         * @param ContextMenuInfo menuInfo
         */
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
        {
             super.onCreateContextMenu(menu, v, menuInfo);
             
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.context_menu, menu);                                       
        }
        
        /**
         * This function allows to set the action for the selected menu item
         * 
         * @author Hyame Alameddine <hyame.alameddine@gmail.com>
         * 
         * @param MenuItem item
         * @return boolean
         */
        @Override
        public boolean onContextItemSelected(MenuItem item)
        {
                //Get the position of the selected item
                AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
                Intent i;
                
            switch (item.getItemId())    
            {
                      case R.id.edit:     
                          i = new Intent(getApplicationContext(), AdduserActivity.class);
                          //pass the position as variable to the AdduserActivity
                          User myUser = new User();    				    	
        			      //get the selected user data
        	  			  ArrayList<Object> dbUserRes = db.getObjectFromPosition(info.position+1, myUser);
        	  			  
        	  			  int id = Integer.parseInt(dbUserRes.get(0).toString());
                          i.putExtra("selectedUserId",id);
                          startActivity(i);
                         break;                   
                      case R.id.delete:     
                        
                          User u = new User();                                          
                          //get the selected user data
                          ArrayList<Object> dbUserDel = db.getObjectFromPosition(info.position+1, u);
                                
                          //set the user id to edit
                          u.setID(Integer.parseInt(dbUserDel.get(0).toString()));
                                
                          //delete user from db
                          db.deleteRow (u);
                                
                          //redirect to users list
                          i = new Intent(getApplicationContext(), UsersListActivity.class);
                          startActivity(i);
                      
                          Toast.makeText(this, "User successfully deleted", Toast.LENGTH_LONG).show();
                  break;                  
            }

          return true;
        }
        
        
         @Override
        protected void onListItemClick(ListView l, View v, int position, long id)
        {
                 if(haveUsers)
                 {
         			Intent i = new Intent(getApplicationContext(), UserInfoActivity.class);
         			User myUser = new User();    				    	
	  			    //get the selected user data
	  	  			ArrayList<Object> dbUserRes = db.getObjectFromPosition(position+1, myUser);
	  	  			  
	  	  			int idInfo = Integer.parseInt(dbUserRes.get(0).toString());        	  			  
                    i.putExtra("selectedUserId",idInfo);
         	     	startActivity(i);
                 }
        }
         
         /**
          * This function create the menu options 
          * @author Rayan Zahab <differentruna@gmail.com> 
          * @param menu
          */
          @Override
         public boolean onCreateOptionsMenu(Menu menu)
         {
             MenuInflater inflater = getMenuInflater();
             inflater.inflate(R.menu.users_list_menu, menu);              
             return true;
     }
          
    /**
      * This function handles clicking any of the menu's items
          * @author Hyame Alameddine <hyame.alameddine@gmail.com> 
          * @param menu
          */
          @Override
          public boolean onOptionsItemSelected(MenuItem item) 
          {       
                  Intent i;
                  
                  switch (item.getItemId()) 
                  {
                   
                  case R.id.add:     
                        i = new Intent(getApplicationContext(), AdduserActivity.class);
                        startActivity(i);
                        break;
                  case R.id.reservations:     
                        i = new Intent(getApplicationContext(), ReservationsListActivity.class);
                        startActivity(i);
                        break;
                  case R.id.conferences:     
                        i = new Intent(getApplicationContext(), RoomsListActivity.class);
                        startActivity(i);
                        break;
                  case R.id.help:     
                        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                        alertDialog.setTitle("Help!");
                        alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
                        alertDialog.setIcon(R.drawable.icon);
                        alertDialog.show();
                        break;
                  case R.id.developers: 
                        Toast.makeText(this, "Rayan,Hyam,Mostafa!", Toast.LENGTH_LONG).show();
                        break;
                    
                  case R.id.logout: 
                        i = new Intent(getApplicationContext(), LoginActivity.class);
                        startActivity(i);
                        break;
                }
                return true;
            }
            
} 